(ns main.waiter-view
  (:use main.views
    main.db
    ring.util.response
    [hiccup page-helpers form-helpers]
    sandbar.stateful-session))

(defn waiter-view [title & content]
  (if (== 0 ((user-session) :inshift))
    (show-error "Your shift is not started, ask manager to sign you in")
  (try
  (if-not (.equals ((user-session) :role) "Waiter")
    (redirect "/")
    (layout title
            [:table.right [:tr [:td [:a {:href "/lock"}"Lock"]]]]
            [:div#clear]
            content
            [:div#clear]))
  (catch NullPointerException e (show-error "Access denied!")))))

(defn create-bill []
  (session-put! :active-bill (.toString (java.util.UUID/randomUUID)))
  (save-bill (session-get :active-bill) ((user-session) :id))
  (redirect "/waiter"))

(defn remove-bill [id]
  (delete-bill id)
  (redirect "/waiter"))

(defn print-bill [id]
  (try
    (update-print-bill id)
    (session-put! :active-bill nil)
    (redirect "/waiter")
    (catch NullPointerException e 
      (show-error "Bill don't exist, maybe you deleted it from another cash register"))))

(defn bill-session []
  (get-bill (session-get :active-bill)))

(defn bill-articles-session []
  (get-articles-from-bill ((bill-session) :id)))

(defn set-active-bill [id]
  (session-put! :active-bill id)
  (redirect "/waiter"))

(defn bill-article-row [a]
  (let [x (get-article (a :article-id))]
    [:tr 
     [:td (x :label)]
     [:td (a :quantity)
      (if (.equals ((user-session) :role) "Waiter")
        (do [:span
             (if-not (.equals (x :instock) 0)
               [:a {:href (str "/waiter/add/" (x :code) "/"
                               ((get-bill (session-get :active-bill)) :id))} 
                [:img.right {:src "/images/up.png" :alt "Increse"}]]
               [:a {:href "#"}[:img.right {:src "/images/upoff.png" :alt "Out of stock"}]])
             [:a {:href (str "waiter/remove/" (x :code) "/"
                             ((get-bill (session-get :active-bill)) :id))} 
              [:img.right {:src "/images/down.png" :alt "Decrese"}]]]))]
     [:td (format-number (x :price))]
     [:td (format "%.2f" (* (a :quantity) (x :price)))]]))

(defn bill-view [x]
  (try 
    (if (> (.size (bill-articles-session)) 0)
      (do
        [:div
        [:img.right {:src "/images/logo.png" :width "100" :height "100"}]
        [:p (str "Waiter: " ((get-user (x :user-id)) :fname) 
                 " " ((get-user (x :user-id)) :lname))]
        [:p (str "Date: " (x :date))]
        [:p (str "Time: " (x :time))]
        [:table.billTable
         [:tr 
          [:td.billCell "Label"]
          [:td.billCell "Quantity"]
          [:td.billCell "Price"]
          [:td.billCell "Total"]]
         (map bill-article-row (bill-articles-session))
         [:tr  
          [:td {:style "text-align: center;"} [:a#button {:href (str "/waiter/printbill/" (x :id))} "Print"]] 
          [:td {:style "text-align: center;"} [:a#button {:href (str "/waiter/removebill/" (x :id))} "Erase"]]
          [:td.bottomCell "Total:"]
          [:td.bottomCell (str (format "%.2f" ((get-bill (session-get :active-bill)) :total)))]]]])
      (do
        [:p "Select articles from list to add"]))
    (catch NullPointerException e [:p "No ative bills"])))

(defn waiter-articles-member [y]
  [:tr 
   [:td (y :label)]
   [:td (format-number (y :price))]
   [:td (y :instock)]
   [:td 
    (if (.equals (y :instock) "/")
      (do
        [:a#button {:href (str "/waiter/add/" (y :code) "/"
                               ((get-bill (session-get :active-bill)) :id))}"Add"])
      (if (< (y :instock) 1)
        [:a#outbutton {:href "#"} "Out of stock"]
        [:a#button {:href (str "/waiter/add/" (y :code) "/"
                               ((get-bill (session-get :active-bill)) :id))}"Add"]))]])

(defn waiter-articles-categs [x]
  [:div
  [:h4 [:a {:href "#"}(x 0)]]
  [:div 
   [:table 
    [:tr
     [:th "Label"][:th "Price"][:th "In stock"][:th "Action"]]
    (map waiter-articles-member (get-articles {:sub-category (x 0)}))]]])

(defn waiter-articles []
  [:div
   (map waiter-articles-categs (group-by :sub-category (get-articles {:category "Kuhinja"})))
   (map waiter-articles-categs (group-by :sub-category (get-articles {:category "Sank"})))])

(defn waiter-menu-member [x]
  [:p [:a {:href (str "/manager/reportsof/"(x :id))} (x :fname) " " (x :lname) " reports"]])

(defn waiter-menu-list []
  (map waiter-menu-member (get-users {:role "Waiter" :inshift 1})))

(defn bill-row [x]
  [:li[:a {:href (str "/waiter/activebill/" (x :id))} 
       (if (.equals (x :id) (session-get :active-bill))
       [:b[:span (str "Bill (" ((get-bill (x :id)) :total) ")")]]
       [:span (str "Bill (" ((get-bill (x :id)) :total) ")")])]])

(defn waiter-bills [user-id]
  [:fieldset [:legend "Unclosed Bills"]
   (if (< (bills-count {:user-id user-id :printed 0}) 1)
     [:p "No active bills"]
        [:ul
         (map bill-row (get-bills {:user-id user-id :printed 0}))])
        [:a.right {:href "/waiter/createbill"} "Create new bill"]])

(defn add-article-to-bill [article-id bill-id]
  (article-increase article-id bill-id)
  (redirect "/waiter"))

(defn remove-article-from-bill [article-id bill-id]
  (article-decrease article-id bill-id)
  (redirect "/waiter"))

(defn waiter-main-view []
  (waiter-view "Waiter"
               (include-js "/scripts/jquery-ui.min.js")
               (include-css "/scripts/jquery.ui.accordion.css")
               (if-not (= nil (bill-session))
                 [:div.left {:id "accordion"}(waiter-articles)])
               [:div.right (waiter-bills ((user-session) :id))]
               [:div.right 
                [:fieldset [:legend "Active bill"]
                 (bill-view (bill-session))]]))
